import requests
import pyttsx3
import time
import tkinter as tk
import csv


class BiliDanmuCrawler:
    def __init__(self, room_id, win):
        self.room_id = room_id
        self.url = f'https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid={self.room_id}&room_type=0'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60',
        }
        self.session = requests.Session()
        f = open('danmu.csv', 'a', encoding='utf-8-sig', newline='')
        csv_writer = csv.DictWriter(f, fieldnames=['昵称', '弹幕', '时间'])
        csv_writer.writeheader()
        self.csv_writer = csv_writer
        self.engine = pyttsx3.Engine()
        self.win = win

    def get_danmu(self):
        response = self.session.get(url=self.url, headers=self.headers)
        data = response.json()
        self.parse_danmu(data)

    def parse_danmu(self, data):
        danmu_list = data['data']['room']
        r = []
        for danmu in danmu_list:
            # 用户名
            nickname = danmu['nickname']
            # 弹幕
            text = danmu['text']
            # 发送时间
            timeline = danmu['timeline']
            print(f'"{nickname}"说：{text}')
            self.speech(f'"{nickname}"说：{text}')
            dit = {
                '昵称': nickname,
                '弹幕': text,
                '时间': timeline,
            }
            self.save_danmu(dit)

    def save_danmu(self, dit):
        self.csv_writer.writerow(dit)

    def speech(self, text):
        self.engine.say(text)      # 告诉演讲引擎说什么
        self.engine.runAndWait()   # 运行演讲引擎
        tk.Label(self.win, text=text).grid(padx=2)

    def run(self):
        while True:
            self.get_danmu()
            time.sleep(5)


if __name__ == '__main__':
    # crawler = BiliDanmuCrawler(room_id=46936)
    # crawler.run()
    pass
